""" System imports """
import os,sys
import logging

""" Other modules """
import pygame

""" Game """

""" Set up logging """
menu_logger = logging.getLogger("epicquest.menu")
menu_logger.debug("Initializing Menu")

class Menu(object):
    """ """
    def __init__(self, font, options, max_shown = 0, handler = None):
        self.font = font
        self.options = options
        self.option = 0
        self.max_shown = max_shown
        if self.max_shown == 0:
            self.max_shown = len(self.options)
        self.low_index = 0
        self.high_index = self.max_shown
        self.height = (self.max_shown+1)*self.font.get_height()
        self.width = 0
        for o in self.options:
            w = (len(o)+1)*self.font.get_width()
            if w > self.width:
                self.width = w
    
    def handle(self, caller):
        if self.handler is not None:
            self.handler.handle(self, caller)
    
    def draw(self, surface, pos, background=None, border=None):
        ypos = pos[1]
        if background:
            pygame.draw.rect(surface, background, (pos[0]-4, pos[1]-4, 
                self.width+8, self.height+6))
        if border:
            pygame.draw.rect(surface, border, (pos[0]-4, pos[1]-4, 
                self.width+8, self.height+6), 1)
        
        i = self.low_index
        for opt in self.options[self.low_index:self.high_index]:
            if i == self.option:
                icon = ">"
            else:
                icon = " "
            ren = self.font.render(icon + opt)
            surface.blit(ren, (pos[0], ypos))
            ypos += ren.get_height()+3
            i += 1
    
    def move_cursor(self, dir):
        if dir > 0:
            if self.option < len(self.options)-1:
                self.option += 1
        elif dir < 0:
            if self.option > 0:
                self.option -= 1
                
        self.high_index = self.option + self.max_shown
        self.low_index = self.option
        if self.high_index > len(self.options):
            self.high_index = len(self.options)
            self.low_index = self.high_index - self.max_shown
        #print str(self.low_index) + " to " + str(self.high_index)
            
            
    def get_option(self):
        return self.option, self.options[self.option]